package com.okbihuo.perm.core.boot.config;

import cn.hutool.json.JSONUtil;
import com.okbihuo.perm.core.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
//@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalResponseConfig implements ResponseBodyAdvice<String> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        final String returnTypeName = methodParameter.getParameterType().getName();
        // 不处理 ResponseEntity和处理好的全局返回值R
        return !ResponseEntity.class.getName().equals(returnTypeName) && !R.class.getName().equals(returnTypeName);
    }

    @Override
    public String beforeBodyWrite(String o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        final String returnTypeName = methodParameter.getParameterType().getName();
        if (mediaType.includes(MediaType.APPLICATION_JSON)) {
            return o;
        }
        if (R.class.getName().equals(returnTypeName) || ResponseEntity.class.getName().equals(returnTypeName)) {
            return o;
        }
        if ("void".equals(returnTypeName)) {
            return R.success("").toJSON();
        }
        return R.data(o).toJSON();
    }
}
